package com.gexiaobao.pigeon.ui.fragment.mine.banking

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Window
import android.view.WindowManager
import androidx.fragment.app.setFragmentResult
import androidx.lifecycle.lifecycleScope
import cn.qqtheme.framework.picker.SinglePicker
import cn.qqtheme.framework.widget.WheelView
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.countDownCoroutines
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.bean.QueryBalanceResponse
import com.gexiaobao.pigeon.app.model.bean.QueryBankListResponse
import com.gexiaobao.pigeon.app.model.param.DepositApplyParam
import com.gexiaobao.pigeon.app.model.param.PayParam
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.SettingUtil
import com.gexiaobao.pigeon.databinding.FragmentAccountWithdrawalBinding
import com.gexiaobao.pigeon.ui.dialog.PayPassDialog
import com.gexiaobao.pigeon.ui.dialog.PayPassView
import com.gexiaobao.pigeon.ui.dialog.RxDialogSingle
import com.gexiaobao.pigeon.ui.dialog.RxPayDialog
import com.gexiaobao.pigeon.ui.view.MyTextWatcher
import com.gexiaobao.pigeon.viewmodel.MineBankingViewModel
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat

/**
 * @Author      : hxw
 * @Date        : 2023/5/31 19:25
 * @Describe    : 提现
 */
class FragmentAccountWithdrawal : BaseFragment<MineBankingViewModel, FragmentAccountWithdrawalBinding>() {

    private var bankCardInfo: ArrayList<QueryBankListResponse.ListBean> = arrayListOf()
    private var payDialog: RxPayDialog? = null
    private var mPosition = 0//记录上次选中位置
    private var mOrderId: Int = 0
    private var investMoneyBean: QueryBankListResponse.ListBean? = null
    private var isResendCode: Boolean = false
    private var withDrawMoney = 0

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewmodel = mViewModel
        mDatabind.includeBar.toolbar.initClose("提现") {
            nav().navigateUp()
        }
        mPosition = KvUtils.decodeInt("position")!!
        investMoneyBean = QueryBankListResponse.ListBean()
        val mData = arguments?.getParcelable<QueryBalanceResponse>(Constant.DATA_BEAN)
        if (mData != null) {
            mViewModel.availableBalances.set(
                SettingUtil.div(
                    mData.allAmount - mData.freezenAmount,
                    100.00,
                    2
                ).toString()
            )
        }
        mDatabind.investMoney.addTextChangedListener(MyTextWatcher(2, mDatabind.investMoney))
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        showLoading(getString(R.string.loading))
        mViewModel.queryBankCard()
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.selectBankCard,
            mDatabind.investMoneyCommit,
            mDatabind.mostMoney
        ) {
            when (it) {
                mDatabind.selectBankCard -> {
                    selectedBank(bankCardInfo)
                }

                mDatabind.mostMoney -> {
                    mDatabind.investMoney.setText(mViewModel.availableBalances.get())
                }

                mDatabind.investMoneyCommit -> {
                    isResendCode = false
                    when {
                        mDatabind.investMoney.text.toString().isEmpty() -> showMessage("请输入提现金额")
                        else -> {
                            withDrawMoney = (mDatabind.investMoney.text.toString().toDouble() * 100).toInt()
                            showLoading(getString(R.string.loading))
                            mViewModel.getWithdrawInfo(withDrawMoney)
                        }
                    }
                }
            }
        }
    }

    override fun createObserver() {
        super.createObserver()
        /** 提现时鸽币抵扣说明 */
        mViewModel.withdrawInfoResult.observe(viewLifecycleOwner) {
            dismissLoading()
            showWithDrawInfoDialog(it.desc)
        }
        /** 查询银行卡列表 */
        mViewModel.queryBankListResult.observe(viewLifecycleOwner) {
            if (!it.isEmpty) {
                if (it.listData?.isNotEmpty() == true) {
                    bankCardInfo.addAll(it.listData)
                    if (mPosition <= it.listData.size - 1) {
                        investMoneyBean = QueryBankListResponse.ListBean(
                            bankCardNo = it.listData[mPosition].bankCardNo,
                            bankName = it.listData[mPosition].bankName,
                            bindTime = it.listData[mPosition].bindTime,
                            cardType = it.listData[mPosition].cardType,
                            bindState = it.listData[mPosition].bindState
                        )
                    } else {
                        investMoneyBean = QueryBankListResponse.ListBean(
                            bankCardNo = it.listData.last().bankCardNo,
                            bankName = it.listData.last().bankName,
                            bindTime = it.listData.last().bindTime,
                            cardType = it.listData.last().cardType,
                            bindState = it.listData.last().bindState
                        )
                    }
                    mDatabind.data = investMoneyBean
                }
            }
        }

        /** 提现 */
        mViewModel.withdrawApplyResult.observe(viewLifecycleOwner) { resultState ->
            dismissLoading()
            parseState(resultState, {
                mOrderId = it.orderId
                if (!isResendCode) {
                    showPayDialog()
                }
            }, {
                RxToast.showToast(it.msg)
            })
        }

        /** 确认支付 */
        mViewModel.payResult.observe(viewLifecycleOwner) { resultState ->
            parseState(resultState, {
                payPassDialog?.dismiss()
                if (payDialog != null && payDialog!!.isShowing)
                    payDialog?.showBottomView()
                workWithResponseData()
            }, {
                payDialog?.dismiss()
                RxToast.showToast(it.msg)
            })
        }
    }

    private fun showWithDrawInfoDialog(desc: String) {
        val dialog = RxDialogSingle(context)
        dialog.setTitle(desc)
        dialog.setSureListener {
            val body = investMoneyBean?.let { it1 ->
                DepositApplyParam(
                    bankCardNo = it1.bankCardNo,
                    money = (mDatabind.investMoney.text.toString().toDouble() * 100).toInt()
                )
            }
            if (body != null) {
                showLoading(getString(R.string.loading))
                mViewModel.withdrawApply(body)
            }
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    @SuppressLint("SetTextI18n")
    private fun workWithResponseData() {
        payDialog?.successAnimDialog()
        payDialog?.setDialogContent("提现成功")
        job = countDownCoroutines(3, {
            payDialog?.sureView?.text = "($it)秒后自动返回"
        }, {
            payDialog?.dismiss()
            onBackToMineBankPage()
            job?.cancel()
        }, lifecycleScope)
        payDialog?.setCancelBtnContent("立即返回")
    }

    private fun onBackToMineBankPage() {
        setFragmentResult("RechargeIsOk", Bundle().apply {
            putBoolean("isOK", true)
        })
        nav().navigateUp()
    }

    var payPassDialog: PayPassDialog? = null

    @SuppressLint("SetTextI18n")
    private fun showPayDialog() {
        payPassDialog = PayPassDialog(context)
        val textWatcherListener = object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {}
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s != null) {
                    val str = "" + s
                    if (str.length == 6) {
                        if (payPassDialog != null) {
                            val split = str.trim().replace(" ", "").split("")
                            if (split.size == 6) {
                                payPassDialog!!.payViewPass.mTvPass[0].text = "" + split[0]
                                payPassDialog!!.payViewPass.mTvPass[1].text = "" + split[1]
                                payPassDialog!!.payViewPass.mTvPass[2].text = "" + split[2]
                                payPassDialog!!.payViewPass.mTvPass[3].text = "" + split[3]
                                payPassDialog!!.payViewPass.mTvPass[4].text = "" + split[4]
                                payPassDialog!!.payViewPass.mTvPass[5].text = "" + split[5]
                                payPassDialog!!.payViewPass.strPass = str
                            } else if (split.size == 8) {
                                payPassDialog!!.payViewPass.mTvPass[0].text = "" + split[1]
                                payPassDialog!!.payViewPass.mTvPass[1].text = "" + split[2]
                                payPassDialog!!.payViewPass.mTvPass[2].text = "" + split[3]
                                payPassDialog!!.payViewPass.mTvPass[3].text = "" + split[4]
                                payPassDialog!!.payViewPass.mTvPass[4].text = "" + split[5]
                                payPassDialog!!.payViewPass.mTvPass[5].text = "" + split[6]
                                payPassDialog!!.payViewPass.strPass = str
                            }
                        }
                    }
                }
            }
        }
        payPassDialog!!.payViewPass.mTvPass[0].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[1].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[2].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[3].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[4].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[5].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.setPayClickListener(object : PayPassView.OnPayClickListener {
            override fun onPaySubmit() {}

            override fun onPayClose() {
                RxToast.showToast("关闭支付")
                payPassDialog!!.dismiss()
            }

            override fun onPayForget() {
                isResendCode = true
                val body = investMoneyBean?.let { it1 ->
                    DepositApplyParam(
                        bankCardNo = it1.bankCardNo,
                        money = (mDatabind.investMoney.text.toString().toDouble() * 100).toInt()
                    )
                }
                if (body != null) {
                    mViewModel.withdrawApply(body)
                }
            }

            override fun onPassFinish(verifyCode: String?) {
//                payPassDialog?.dismiss()
                showPayAnimDialog()
                job = countDownCoroutines(1, {

                }, {
                    val body = PayParam(mOrderId, verifyCode.toString())
                    mViewModel.commitPay(body)
                }, lifecycleScope)

            }
        })
    }

    private fun showPayAnimDialog() {
        payDialog = RxPayDialog(context)
        payDialog!!.loadingDialog()
        payDialog!!.setCancelListener {
            try {
                job?.cancel()
                payDialog!!.dismiss()
            } catch (_: Exception) {
            }
        }
        payDialog!!.setCanceledOnTouchOutside(false)
        payDialog!!.setFullScreenWidth()
        payDialog!!.show()
    }


    private fun selectedBank(bankList: ArrayList<QueryBankListResponse.ListBean>) {
        val picker = SinglePicker(activity, bankList)
        picker.setCanceledOnTouchOutside(false)
        picker.setDividerRatio(WheelView.DividerConfig.FILL)
        picker.setShadowColor(Color.rgb(9, 155, 251), 40)
        picker.setCycleDisable(true)
        picker.setTitleText("请选择银行卡")
        picker.setTitleTextColor(Color.BLACK)
        picker.setTitleTextSize(18)
        picker.setSubmitText("确认")
        picker.setSubmitTextSize(17)
        picker.setSubmitTextColor(Color.rgb(9, 155, 251))//确定按钮文字颜色
        picker.setCancelText("取消")
        picker.setCancelTextSize(17)
        picker.setCancelTextColor(Color.rgb(9, 155, 251))//取消按钮文字颜色
        picker.setTextSize(18)
        picker.setLineSpaceMultiplier(3.0F)
        picker.setOnItemPickListener { index, item ->
            KvUtils.encode("position", index)
            investMoneyBean =
                QueryBankListResponse.ListBean(
                    bankCardNo = item.bankCardNo,
                    bankName = item.bankName,
                    bindTime = item.bindTime,
                    cardType = item.cardType,
                    bindState = item.bindState
                )
            mDatabind.data = investMoneyBean
        }
        val window: Window = picker.window
        val lp: WindowManager.LayoutParams = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        picker.setWidth(WindowManager.LayoutParams.MATCH_PARENT)
        picker.show()
    }
}